from smssendfun import sms_send_one
from hostcollector import LinuxHosts
import json

# 以下 需放在配置文件内
linuxhostlist = {
"zzjfdb1":{
"ip":"10.212.9.244",
"port":"10022"
},
"zzjfdb2":{
"ip":"10.212.9.245",
"port":"10022"
},
"zzjfapp1":{
"ip":"10.212.9.102",
"port":"10022"
},
"zzjfapp2":{
"ip":"10.212.9.176",
"port":"10022"
},
"zzjfapp3":{
"ip":"10.212.9.177",
"port":"10022"
}
}

# 以下 只留下信息采集，告警写在另一个文件中，使用告警类
for name in linuxhostlist:
    hostname = name
    hostip = linuxhostlist[name]["ip"]
    pt = linuxhostlist[name]["port"]
    server = LinuxHosts(hostip, hostname=hostname, port=pt)
    if server.check_host_ping():
        print(server.check_host_cpu_usage())
        print(server.check_host_mem_usage())
    else:
        smscontent = hostip + ' 无法访问'
        sms_send_one('admin', '13659311603', smscontent)
        print('admin' + hostip)
    with open('collogs/hostrunninglogs.json', 'r') as jsonfile:
        datajson = json.load(jsonfile)
        cpuusage = datajson["hostlist"][hostname]["cpuusage"]
        cpunsum = 0
        for n in cpuusage:
            cpunsum += float(n)
        cpuavg = round(cpunsum/len(cpuusage), 2)
        if cpuavg > 89:
            smscontent = hostip + ' cpu使用率过高.当前使用率 ' + str(cpuavg) + '%'
            sms_send_one('admin', '13659311603', smscontent)
        memusage = datajson["hostlist"][hostname]["memusage"] 
        memnsum = 0
        for n in memusage:
            memnsum += float(n)
        memavg = round(memnsum/len(memusage), 2)
        if memavg > 90:
            smscontent = hostip + ' 内存使用率过高.当前使用率 ' + str(memavg) + '%'
            sms_send_one('admin', '13659311603', smscontent)
